package com.kly.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.kly.constants.UserContext;
import com.kly.domain.dto.user.UserDto;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.kly.constants.RedisConstant.USER_LOGIN_INFO_KEY;
import static com.kly.constants.RedisConstant.USER_LOGIN_INFO_TTL;

/**
 * @author admin
 * @date 2025/3/16
 */
public class LoginInterceptor implements HandlerInterceptor {


    private final StringRedisTemplate stringRedisTemplate;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        // 1. 获取请求头信息
        String token = request.getHeader("Token");
        // 2. 判断用户是否登录
        // 拼接token
        if(StrUtil.isNotBlank(token)) {
            String key = USER_LOGIN_INFO_KEY + token;
            Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
            UserDto userDto = BeanUtil.fillBeanWithMap(userMap, new UserDto(), false);
            // 刷新token
            stringRedisTemplate.expire(key, USER_LOGIN_INFO_TTL, TimeUnit.SECONDS);
            // 登录则放行
            UserContext.setUser(userDto);
            return true;
        }


        // 刷新token
        // 3. 登录则放行
        // Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        // UserDto userDto = (UserDto) userObj;
        // UserContext.setUser(userDto);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}
